package com.zkr.service;

import java.util.List;
import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;

import com.zkr.mapper.UserMapper;
import com.zkr.pojo.User;
import com.zkr.vo.UserResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;


/**
 *
 * 功能描述:
 * @author:mayue
 * @date: 2018/8/29 下午 9:12
 * @param:
 * @return:
 * @throws:
 *
 */
@Service
public class UserServiceImpl implements UserService {
	@Autowired
	private UserMapper userMapper;
//	@Autowired
//	private RedisTemplate<String, User> redisTemplate;

	@Resource
	private RedisTemplate<String, UserResult> redisTemplate;
	
	@Override
	public User findById(Integer id) {
		UserResult userResult=new UserResult();
		User user=new User();
		String key="user";
		boolean hasKey = redisTemplate.hasKey(key);
		// 从缓存中取
		if (hasKey) {
			userResult = redisTemplate.opsForValue().get(key);
            user=userResult.getUser();
            System.out.println("获得了用户!!!!");
            return user;
        }
        user=userMapper.findById(id);
		userResult.setUser(user);
		redisTemplate.opsForValue().set(key, userResult, 600, TimeUnit.SECONDS);
		return user;
	}
	/**
	 *
	 * 功能描述: 查询所有用户信息
	 * @author:mayue
	 * @date: 2018/8/29 下午 9:12
	 * @param: []
	 * @return: java.util.List<com.zkr.pojo.User>
	 * @throws:
	 *
	 */
	@Override
	public UserResult find() {
		UserResult userResult=new UserResult();
		String key="userAll";
		boolean hasKey = redisTemplate.hasKey(key);
		// 从缓存中取
		if (hasKey) {
			userResult = redisTemplate.opsForValue().get(key);
			System.out.println("从缓存中获得了用户!!!!");
			return userResult;
		}
		List<User> userList=userMapper.find();
		userResult.setUserResult(userList);
		redisTemplate.opsForValue().set(key, userResult, 600, TimeUnit.SECONDS);
		System.out.println("加入了缓存！！！");

		return userResult;
	}

	@Override
	public void saveUser(User user) {
		System.out.println("imp:"+user);
		userMapper.saveUser(user);
	}
}
